package jp.co.hcs.attendancemanagement.dialog.action;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jp.co.hcs.attendancemanagement.AMConstants;
import jp.co.hcs.attendancemanagement.action.AMAction;
import jp.co.hcs.attendancemanagement.data.entity.EmployeeMaster;
import jp.co.hcs.attendancemanagement.dialog.logic.DepartmentListLogic;
import jp.co.hcs.attendancemanagement.dialog.logic.GetEmployeeLogic;
import jp.co.hcs.attendancemanagement.dialog.logic.dto.DepartmentDTO;
import net.sf.json.JSONArray;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * The Class DepartmentListAction.
 */
public class DepartmentListAction extends AMAction {

  public ActionForward executeImpl(ActionMapping mapping, ActionForm form,
      HttpServletRequest request, HttpServletResponse response) throws Exception {

    response.setContentType("text/json");

    String divisionSelected = request.getParameter("division");
    String currentDept = "";

    if (divisionSelected == null) {
      String userId = (String) request.getSession().getAttribute(AMConstants.USER_LOGGED_IN);
      GetEmployeeLogic empLogic = new GetEmployeeLogic();
      EmployeeMaster employee = empLogic.getEmployeeById(userId);
      divisionSelected = employee.getDivisionId();
      currentDept = employee.getDepartmentId();
    }

    DepartmentListLogic logic = new DepartmentListLogic();
    List<DepartmentDTO> listDepts =
        logic.getDepartmentListByDivisionId(divisionSelected, currentDept);

    JSONArray jsonArray = JSONArray.fromObject(listDepts);

    PrintWriter pw = response.getWriter();
    pw.write("{\"listDepts\":" + jsonArray.toString() + "}");
    pw.flush();
    pw.close();

    return null;
  }

}
